package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.CustomerConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.domain.business.BusinessCustomerDO;
import com.qk.domain.customers.CustomersDO;
import com.qk.domain.user.UserDO;
import com.qk.dto.customer.CustomerAddDTO;
import com.qk.dto.customer.CustomerDTO;
import com.qk.entity.Business;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.service.CustomersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class CustomersServiceImpl extends ServiceImpl<BusinessMapper, Business> implements CustomersService {
    @Autowired
    private BusinessMapper businessMapper;
    @Override
    public PageResult<CustomersDO> list(CustomerDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        List<CustomersDO> result = businessMapper.selectByPage(dto);
        Page<CustomersDO> page = (Page<CustomersDO>) result;
        for (CustomersDO customer : page.getResult()) {
            if (customer.getPhone() != null) {
                String hiddenPhone = StrUtil.hide(customer.getPhone(), 3, 7);
                customer.setPhone(hiddenPhone); // 将脱敏后的手机号设置回对象
            }
        }
        return PageResult.<CustomersDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addCustomer(CustomerAddDTO dto) {
        log.info("添加客户：{}", dto);
        boolean hasNullField = BeanUtil.hasNullField(dto, "name", "phone");
        if (hasNullField){
            log.error("参数有误");
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(CustomerConstants.TO_CUSTOMERS);
        business.setSourceType(2); // 标识为直接创建的客户
        this.save(business);
    }

    @Override
    public BusinessCustomerDO getByCusId(Integer id) {
        return businessMapper.getByCusId(id);
    }

    @Override
    public void updateBy(BusinessCustomerDO dto) {
        log.info("更新客户：{}", dto);
        dto.setUpdateTime(LocalDateTime.now());
        businessMapper.updateBy(dto);
    }

}
